<%- contentFor('mainContent') %>

<!-- Page content-->
<div class="row justify-content-center">
    <div class="col-md-6">
        <h2 class="mb-4">用户登录</h2>
        <div class="mb-3 card-body"></div>
        <form action="/login" method="post">
            <div class="mb-3">
                <label class="form-label">用户名</label>
                <input type="text" class="form-control" name="username" id="username" required>
            </div>
            <div class="mb-3">
                <label class="form-label">密码</label>
                <input type="password" class="form-control" name="password" id="password" required>
            </div>
            <div class="mb-3">
                <button type="submit" class="btn btn-primary w-100">登录</button>
            </div>
        </form>
        <div class="mb-3">
            <a href="/register" class="btn btn-link w-100">去注册>></a>
        </div>
    </div>
</div>

<%- contentFor('pageJS') %>
<script>
    document.querySelector('form').addEventListener('submit', async function (e) {
        e.preventDefault();

        // 禁用提交按钮
        const submitBtn = this.querySelector('button[type="submit"]');
        submitBtn.disabled = true;
        submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 提交中...';

        // 清除旧错误提示
        document.querySelectorAll('.alert').forEach(alert => alert.remove());

        // 密码一致性验证
        const password = document.getElementById('password').value;

        try {
            const response = await fetch('/api/login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: new URLSearchParams(new FormData(this))
            });

            const result = await response.json();
            if (result.code === '0000') {
                window.location.href = '/list';
            } else {
                showError(result.msg || '登录失败');
            }
        } catch (error) {
            showError('网络请求异常');
        } finally {
            submitBtn.disabled = false;
            submitBtn.textContent = '用户登录';
        }
    });

    function showError(message) {
        const errorDiv = document.createElement('div');
        errorDiv.className = 'alert alert-danger mt-3';
        errorDiv.textContent = message;
        document.querySelector('.card-body').appendChild(errorDiv);
        setTimeout(() => {
            errorDiv.remove();
        }, 5000)
    }

</script>